package com.eight.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eight.common.pojo.*;
import com.eight.common.vo.Result;
import com.eight.order.config.AlipayConfig;
import com.eight.order.dao.OrderDao;
import com.eight.order.dao.PayLogDao;
import com.eight.order.dao.TbMemberDao;
import com.eight.order.dao.TbPlayHistoryDao;
import com.eight.order.service.OrderService;
import com.eight.order.utils.HttpClient;
import com.eight.order.vo.OrderVo;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @program: qy8-education
 * @description:
 * @author: 郑友民（1460115388@qq.com）
 * @create: 2023-06-01 20:09
 **/
@Service
@EnableScheduling
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private PayLogDao payLogDao;
    @Resource
    private TbMemberDao tbMemberDao;
    @Override
    public Page<Order> getAllOrder(Integer current, Integer pageSize, OrderVo orderVo) {
        Page<Order> page = new Page<>(current, pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        if (orderVo.getStatus() != null) {
            wrapper.eq("status", orderVo.getStatus());
        }
        if (StringUtils.hasText(orderVo.getMobile())) {
            wrapper.eq("mobile", orderVo.getMobile());
        }
        orderDao.selectPage(page, wrapper);
        return page;
    }

    @Override
    public int deleteOrder(String id) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        int delete = orderDao.delete(wrapper);
        return delete;
    }

    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result createWeiXin(String courseId, String huiYuanId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", huiYuanId);
        wrapper.eq("course_id", courseId);
        wrapper.eq("status", 0);
        wrapper.eq("is_deleted", 0);
        wrapper.gt("gmt_modified", LocalDateTime.now());
        Order order = orderDao.selectOne(wrapper);
        if (order == null) {
            //创建订单
            Order order1 = orderDao.createOrder(courseId);
            TbMember tbMember = tbMemberDao.selectById(huiYuanId);
            order1.setId(IdUtil.getSnowflakeNextId() + "");
            order1.setCourseId(courseId);
            order1.setMemberId(huiYuanId);
            order1.setNickname(tbMember.getNickname());
            order1.setMobile(tbMember.getMobile());
            order1.setGmtCreate(LocalDateTime.now());
            order1.setGmtModified(LocalDateTime.now().plusMinutes(30L));
            order1.setOrderNo(IdUtil.getSnowflakeNextId() + "");
            order1.setPayType(0);
            order1.setStatus(0);
            order1.setIsDeleted(0);
            order = order1;
            orderDao.insert(order1);
            PayLog payLog= new PayLog();
            payLog.setGmtCreate(LocalDateTime.now());
            payLog.setGmtModified(LocalDateTime.now());
            payLog.setId(IdUtil.getSnowflakeNextId()+"");
            payLog.setOrderNo(order.getOrderNo());
            payLog.setTotalFee(new BigDecimal(String.valueOf(order.getTotalFee())));
            payLog.setIsDeleted(0);
            payLogDao.insert(payLog);
        }
        try {
            //设置请求的参数---式为xmL格式
            Map<String, String> params = new HashMap<>();
            //请求参数
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("body", order.getCourseTitle());
            params.put("out_trade_no", order.getOrderNo());
            params.put("total_fee", 1 + "");
            //未来写成项目部署的ip
            params.put("spbill_create_ip", "127.0.0.1");
            params.put("notify_url", "http://localhost:9000/order/order");
            params.put("trade_type", "NATIVE");
            //创建HttpcLient对象 作用远程调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //支持https协议
            client.setHttps(true);
            //设置请求的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            client.post();
            //获取请求的响应结果
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("result_code").equals("SUCCESS")) {
                Map<String, Object> result = new HashMap<>();
                result.put("code_url", map.get("code_url"));
                result.put("total_fee", order.getTotalFee());
                result.put("out_trade_no", order.getOrderNo());
                result.put("course_id", order.getCourseId());

                return Result.success(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail();
    }


    @Override
    public Result getPayStatus(String orderNo) {
        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置请求的参数---式为xmL格式
            Map<String, String> params = new HashMap<>();
            //请求参数
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("out_trade_no", orderNo);
            //支持https协议
            client.setHttps(true);
            //设置请求的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            client.post();
            //获取请求的响应结果
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")) {
                //修改订单状态
                Order order = new Order();
                order.setStatus(1);
                order.setGmtModified(LocalDateTime.now());
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("order_no", orderNo);
                wrapper.eq("status", 0);
                orderDao.update(order, wrapper);
                //    修改订单记录
                PayLog payLog = new PayLog();
                payLog.setPayTime(LocalDateTime.now());
                payLog.setGmtModified(LocalDateTime.now());
                payLog.setTransactionId(map.get("transaction_id"));
                payLog.setTradeState("SUCCESS");
                QueryWrapper<PayLog> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_no", orderNo);
                payLogDao.update(payLog, queryWrapper);
                return Result.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.fail();
    }

    @Resource
    private TbPlayHistoryDao tbPlayHistoryDao;

    @Override
    public Page<TbPlayHistory> queryPlayHistoryBy(Integer currentPage, Integer pageCount, String memberId) {
        Page<TbPlayHistory> page = new Page<>(currentPage, pageCount);
        QueryWrapper<TbPlayHistory> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(memberId)) {
            wrapper.eq("user_id", memberId);
        }
        tbPlayHistoryDao.findPage(page, wrapper);
        return page;
    }

    @Scheduled(fixedDelay = 600000)
    public void dingShi(){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        List<Order> orders = orderDao.selectList(wrapper);
        for (Order order : orders) {
            if(order.getGmtModified().isBefore(LocalDateTime.now())){
                order.setIsDeleted(1);
                orderDao.updateById(order);
            }
        }

    }
}

